package com.ctyon.watchmanager.ui.fragment;

import android.Manifest;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.android.arouter.launcher.ARouter;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdate;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.ctyon.common.event.LocationMessageEvent;
import com.ctyon.common.util.DataUtil;
import com.ctyon.common.util.TSnackbarUtil;
import com.ctyon.netlibrary.net.revert.BaseResponseEntity;
import com.ctyon.netlibrary.use.BaseObserver;
import com.ctyon.watchmanager.BasicApp;
import com.ctyon.watchmanager.R;
import com.ctyon.watchmanager.databinding.FragmentMapBinding;
import com.ctyon.watchmanager.model.net.service.NetService;
import com.ctyon.watchmanager.present.MapPresenter;
import com.ctyon.watchmanager.service.BgService;
import com.ctyon.watchmanager.ui.BaseFragment;
import com.orhanobut.logger.Logger;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.concurrent.TimeUnit;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static com.ctyon.common.container.ARouterPath.ROUTER_ACTIVITY_CONTAINER;
import static com.ctyon.watchmanager.service.BgService.TYPE_MQTT;
import static com.ctyon.watchmanager.ui.activity.ContainerActivity.TAB_INDEX_PARAM;

/**
 * CreateDate：19-6-25 on 上午9:14
 * Describe:
 * Coder: lee
 */
public class MapFragment extends BaseFragment {

    public static final String TAG = "MapFragment";

    public static final String LON = "lon";
    public static final String DIM = "dim";

    private FragmentMapBinding mBinding;
    private AMap aMap;
    private UiSettings mUiSettings;

    private AMapLocationClient mLocationClient;
    private AMapLocationClientOption mLocationOption;
    private Marker locationMarker;
    private Marker myMarker;

    public static MapFragment newInstance(String lon, String dim) {
        final MapFragment fragment = new MapFragment();
        final Bundle args = new Bundle();
        args.putString(LON, lon);
        args.putString(DIM, dim);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_map, container, false);
        mBinding.setMapPresenter(mapPresenter);
        mBinding.map.onCreate(savedInstanceState);

        return mBinding.getRoot();

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (aMap == null) {
            aMap = mBinding.map.getMap();
            mUiSettings = aMap.getUiSettings();
            mUiSettings.setZoomControlsEnabled(true);//控制缩放按钮是否显示
            mUiSettings.setZoomPosition(1);//设置缩放按钮的位置
            mUiSettings.setScaleControlsEnabled(true);//控制比例尺控件是否显示

//            aMap.setLocationSource(this);//通过aMap对象设置定位数据源的监听
//            mUiSettings.setMyLocationButtonEnabled(true); //显示默认的定位按钮
//            aMap.setMyLocationEnabled(true);// 可触发定位并显示当前位置

            //初始化定位
            mLocationClient = new AMapLocationClient(BasicApp.getInstance().getApplicationContext());
            //设置定位回调监听
            mLocationClient.setLocationListener(mLocationListener);
            mLocationOption = new AMapLocationClientOption();
            //获取一次定位结果：
            //该方法默认为false。
            mLocationOption.setOnceLocation(true);

            //获取最近3s内精度最高的一次定位结果：
            //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
            mLocationOption.setOnceLocationLatest(true);
            //设置是否返回地址信息（默认返回地址信息）
            mLocationOption.setNeedAddress(false);
            //给定位客户端对象设置定位参数
            mLocationClient.setLocationOption(mLocationOption);

            Observable.timer(1, TimeUnit.SECONDS)
                    .subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(aLong -> {
                        String lon = getArguments().getString(LON);
                        String dim = getArguments().getString(DIM);
                        mapCenter(lon, dim, true);
                        mapPresenter.onLocationNowClick();
                    });
        }
    }

    private final MapPresenter mapPresenter = new MapPresenter() {
        @Override
        public void onLocationClick() {
            new RxPermissions(getActivity()).request(
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    .subscribe(granted -> {
                        Logger.i("rxPermissions : granted = " + granted);
                        if (granted) { // Always true pre-M
                            Logger.d("startBgService");
                            TSnackbarUtil.TSBSuccessLong(getActivity(), "正在获取您的位置,请稍候...");
                            //启动定位
                            mLocationClient.startLocation();
                        } else {
                            Logger.d("rxPermissions failed");
                            TSnackbarUtil.TSBError(getActivity(), "请打开定位权限");
                        }
                    });
        }

        @Override
        public void onLocationHistoryClick() {
            ARouter.getInstance().build(ROUTER_ACTIVITY_CONTAINER)
                    .withString(TAB_INDEX_PARAM, MapHistoryFragment.TAG)
                    .navigation();

        }

        @Override
        public void onLocationNowClick() {
            final String method = "locationNow";
            if (NetService.getInstance().isDisable(method)) {
                TSnackbarUtil.TSBError(getActivity(), "请稍候...");
                return;
            }
            NetService.getInstance()
                    .locationNow(BasicApp.getInstance().getManager().getManagerId(), BasicApp.getInstance().getWatch().getMeid())
                    .timeout(10, TimeUnit.SECONDS)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new BaseObserver<BaseResponseEntity>() {
                        @Override
                        public void onSuccess(BaseResponseEntity responseEntity) {
                            Logger.d("onSuccess : " + responseEntity.toString());
                            TSnackbarUtil.TSBSuccess(getActivity(), "已向手表发送定位指令");
                            mBinding.setLocationHint("正在获取位置信息");
                        }

                        @Override
                        public String onOver() {
                            return method;
                        }
                    });
        }
    };

    //声明定位回调监听器
    private final AMapLocationListener mLocationListener = aMapLocation -> {
        Logger.t(LTAG).i(aMapLocation.toString());

        if (aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {

                mBinding.setLocationHint("位置信息已更新");
                TSnackbarUtil.TSBSuccess(getActivity(), "获取您的位置信息成功");
                //定位成功回调信息，设置相关消息
                //取出经纬度
                LatLng latLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());

                if (myMarker == null) {
                    MarkerOptions markerOption = new MarkerOptions();
                    markerOption.position(latLng);
                    markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_location_me)));

                    //如果是空的添加一个新的,icon方法就是设置定位图标，可以自定义
                    myMarker = aMap.addMarker(new MarkerOptions().position(latLng));
                } else {
                    //已经添加过了，修改位置即可
                    myMarker.setPosition(latLng);
                }
                //然后可以移动到定位点,使用animateCamera就有动画效果
                aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));

            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("AmapError", "location Error, ErrCode:"
                        + aMapLocation.getErrorCode() + ", errInfo:"
                        + aMapLocation.getErrorInfo());
            }
        }
    };

    private void loadData() {
        if (null == BasicApp.getInstance().getWatch()) {
            return;
        }
        if (0 < BasicApp.getInstance().getWatch().getLocationTime()) {
            mBinding.setLocationTime(DataUtil.getDateToString(BasicApp.getInstance().getWatch().getLocationTime(), "yyyy-MM-dd HH:mm:ss"));
        }
        int battery = BasicApp.getInstance().getWatch().getBattery();
        mBinding.setBattery(battery + "%");
        refreshBattery(battery);
        mBinding.setLocation(BasicApp.getInstance().getWatch().getLocation());
    }

    private void refreshBattery(int battery) {
        if (battery <= 5){
            mBinding.setBatteryIcon(getResources().getDrawable(R.mipmap.ic_battery0));
        } else if (battery <= 15){
            mBinding.setBatteryIcon(getResources().getDrawable(R.mipmap.ic_battery1));
        }else if (battery <= 40){
            mBinding.setBatteryIcon(getResources().getDrawable(R.mipmap.ic_battery2));
        }else if (battery <= 60){
            mBinding.setBatteryIcon(getResources().getDrawable(R.mipmap.ic_battery3));
        }else if (battery <= 80){
            mBinding.setBatteryIcon(getResources().getDrawable(R.mipmap.ic_battery4));
        }else if (battery <= 100){
            mBinding.setBatteryIcon(getResources().getDrawable(R.mipmap.ic_battery5));
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    public void onLocation(LocationMessageEvent messageEvent) {
        mBinding.setLocationHint("位置信息已更新");
        mBinding.setLocation(messageEvent.getLocation());
        mBinding.setLocationTime(DataUtil.getDateToString(BasicApp.getInstance().getWatch().getLocationTime(), "yyyy-MM-dd HH:mm:ss"));
        mapCenter(messageEvent.getLon(), messageEvent.getDim(), true);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != mLocationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            mLocationClient.onDestroy();
            mLocationClient = null;
            mLocationOption = null;
        }
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mBinding.map.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mBinding.map.onResume();
        loadData();
    }

    @Override
    public void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mBinding.map.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mBinding.map.onSaveInstanceState(outState);
    }

    private void mapCenter(String lon, String dim, boolean center) {
        Logger.t(LTAG).i("lon = " + lon + "  dim = " + dim);
        if (!DataUtil.isEmptyOr(lon, dim)) {
            LatLng latLng = new LatLng(Double.valueOf(lon), Double.valueOf(dim));
            //添加Marker显示定位位置
            if (locationMarker == null) {

                MarkerOptions markerOption = new MarkerOptions();
                markerOption.position(latLng);
                markerOption.icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_location_watch)));
                // 将Marker设置为贴地显示，可以双指下拉地图查看效果
                //如果是空的添加一个新的,icon方法就是设置定位图标，可以自定义
                locationMarker = aMap.addMarker(markerOption);
            } else {
                //已经添加过了，修改位置即可
                locationMarker.setPosition(latLng);
            }
            if (center) {
                //然后可以移动到定位点,使用animateCamera就有动画效果
                aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
            }
            //参数依次是：视角调整区域的中心点坐标、希望调整到的缩放级别、俯仰角0°~45°（垂直与地图时为0）、偏航角 0~360° (正北方为0)
//            CameraUpdate mCameraUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(latLng, 15, 30, 0));
//            aMap.animateCamera(mCameraUpdate);
        }
    }

}
